package com.base.myproject.client.HR.bcode;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class Bcode_SoftManager extends BaseJDBCPanel{

	private BaseStore<BusiObject> mainstore = null;
	private BaseStore<BusiObject> store = null;
	private BaseGrid<BusiObject> grid = null;
	private Button btnOpen = new Button("开通");
	private Button btnCancel = new Button("取消");
	private BaseComboBoxX bcbSoftName = new BaseComboBoxX("name","dictionary","where type = 'soft_manager'");
	private String Operator = "";
	
	public Bcode_SoftManager(BaseStore<BusiObject> mainstore) {
		this.mainstore = mainstore;
		init();
	}
	
	public void init() {
		initWidget();
		Operator = Env.getEnvbcode();
	}

	private void initWidget() {
		VerticalPanel v = new VerticalPanel();
		HorizontalPanel h = new HorizontalPanel();
		h.setSpacing(3);
		FieldSet fs = new FieldSet();
		fs.setHeading("帐号开通/取消");
		btnOpen.addListener(Events.OnClick, getListener());
		btnCancel.addListener(Events.OnClick, getListener());
		h.add(btnOpen);
		h.add(btnCancel);
		fs.add(h);
		v.setSpacing(5);
		v.add(fs);
		v.add(getGrid());
		this.add(v);
	}
	
	public BaseStore<BusiObject> getStore(){
		if(store==null) {
			createStore();
		}
		return store;
	}
	
	private BaseStore<BusiObject> createStore(){
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("HRJ9_bcode");
		type.getField("HRJ9_bcode").setType(String.class);
		type.addField("Soft_name");
		type.getField("Soft_name").setType(String.class);
		type.addField("Soft_username");
		type.getField("Soft_username").setType(String.class);
		type.addField("Soft_password");
		type.getField("Soft_password").setType(String.class);
		type.addField("Username_stauts");
		type.getField("Username_stauts").setType(String.class);
		type.addField("permissions");
		type.getField("permissions").setType(String.class);
		type.addField("App_type");
		type.getField("App_type").setType(String.class);
		type.addField("App1");
		type.getField("App1").setType(String.class);
		type.addField("App2");
		type.getField("App2").setType(String.class);
		type.addField("IPAddress");
		type.getField("IPAddress").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("bcode_softmanager");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from bcode_softmanager where HRJ9_bcode = '{bcode}'");
		info.setParent(mainstore);
		info.setLinkparentcolumns(new String[] { "bcode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "HRJ9_bcode" });// 关联子表字段
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}
	
	private BaseGrid<BusiObject> getGrid(){
		return createGrid();
	}
	
	private ColumnConfig C4 = null;
	private ColumnConfig C11 = null;
	
	private BaseGrid<BusiObject> createGrid(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C3 = new ColumnConfig("HRJ9_bcode", "Bcode", 80);
//		TextField<String> t3 = new TextField<String>();
//		t3.setName("HRJ9_bcode");
//		C3.setEditor(new CellEditor(t3));
		columns.add(C3);
		
		C4 = new ColumnConfig("Soft_name", "软件名称", 80);
		C4.setEditor(bcbSoftName.getCellEditor());
		columns.add(C4);
		
		ColumnConfig C5 = new ColumnConfig("Soft_username", "要求用户名", 80);
		TextField<String> t5 = new TextField<String>();
		t5.setName("Soft_username");
		C5.setEditor(new CellEditor(t5));
		columns.add(C5);
		
		ColumnConfig C6 = new ColumnConfig("Username_stauts", "账号状态", 80);
	   // C6.setEditor(new CellEditor(dateField6));
		columns.add(C6);
		
		//ColumnConfig C7 = new ColumnConfig("permissions	", "账号权限", 80);
	   // C7.setEditor(new CellEditor(dateField7));
		//columns.add(C7);
		
	//	ColumnConfig C8 = new ColumnConfig("App_type", "申请类型", 80);
	    //C8.setEditor(new CellEditor(dateField8));
	//	columns.add(C8);
		
		ColumnConfig C9 = new ColumnConfig("App1", "审批状态1", 80);
		//C9.setEditor(new CellEditor(t9));
		columns.add(C9);
		
		ColumnConfig C10 = new ColumnConfig("App2", "审批状态2", 80);
		//C9.setEditor(new CellEditor(t9));
		columns.add(C10);
		
		C11 = new ColumnConfig("IPAddress","服务器IP地址",120);
		TextField<String> t11 = new TextField<String>();
		t11.setName("IPAddress");
		C11.setEditor(new CellEditor(t11));
		columns.add(C11);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.setSelectionModel(cbs);
		grid.setWidth(700);
		grid.setHeight(350);
		grid.addListener(Events.OnClick, getListener());
		return grid;
	}
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	private Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}
		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							
						} else if (be.getType() == Events.OnClick) {
							if(be.getSource().equals(btnOpen)){
								if(grid.getSelectionModel().getSelectedItem() != null){
									String softName = grid.getSelectionModel().getSelectedItem().get("Soft_name");
									String softUserName = grid.getSelectionModel().getSelectedItem().get("Soft_username");
									String ip = grid.getSelectionModel().getSelectedItem().get("IPAddress") == null ? "" : grid.getSelectionModel().getSelectedItem().get("IPAddress").toString();
									if(softName.equals("PMS")){
										commandPMS(ip,softUserName,Operator,"A");
										String sql = "update bcode_softmanager set Username_stauts='有效' where HRJ9_bcode='"+mainstore.getValue("bcode")+"' and Soft_name = '"+softName+"'";
										commandSql(sql);
										store.reload();
									}else if(softName.equals("POS")){
										commandPOS(softUserName,1);
										String sql = "update bcode_softmanager set Username_stauts='有效' where HRJ9_bcode='"+mainstore.getValue("bcode")+"' and Soft_name = '"+softName+"'";
										commandSql(sql);
										store.reload();
									}								}
							}else if(be.getSource().equals(btnCancel)){
								if(grid.getSelectionModel().getSelectedItem() != null){
									String softName = grid.getSelectionModel().getSelectedItem().get("Soft_name");
									String softUserName = grid.getSelectionModel().getSelectedItem().get("Soft_username");
									String ip = grid.getSelectionModel().getSelectedItem().get("IPAddress");
									if(softName.equals("PMS")){
										commandPMS(ip,softUserName,Operator,"D");
										String sql = "update bcode_softmanager set Username_stauts='无效' where HRJ9_bcode='"+mainstore.getValue("bcode")+"' and Soft_name = '"+softName+"'";
										commandSql(sql);
										store.reload();
									}else if(softName.equals("POS")){
										commandPOS(softUserName,0);
										String sql = "update bcode_softmanager set Username_stauts='无效' where HRJ9_bcode='"+mainstore.getValue("bcode")+"' ";
										commandSql(sql);
										store.reload();
									}								}
							}else if(be.getSource().equals(grid)){
								if(grid.getSelectionModel().getSelectedItem() != null){
									String status = grid.getSelectionModel().getSelectedItem().get("Username_stauts");
									if(status == null){
										
									}else if(status.equals("有效")){
										btnOpen.setEnabled(false);
									}else
										btnOpen.setEnabled(true);
									if(status == null){
										
									}else if(status.equals("无效")){
										btnCancel.setEnabled(false);
									}else
										btnCancel.setEnabled(true);
								}
							}
						} else if (be.getType() == Events.Change) {

						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	
	private void commandPMS(String ip,String softUserName,String Operator,String status){
		if(ip.equals("127.0.0.1") || ip == ""){
			MessageBox.alert("TEST", ip, null);
			String sql = "exec HPMS_SysMtn_DisableAasUser @Param_UserStatus='"+status+"'," +
					"@Param_RecUid='"+softUserName+"'@Param_OPerator='"+Operator+"',";
			commandSql(sql);
		}else{
			String sql1 = "exec sp_addlinkedserver 'srv_lnk','','SQLOLEDB','"+ip+"'";
			String sql2 = "exec sp_addlinkedsrvlogin 'srv_lnk','false',null,'sa','jll'";
			String sql3 = "exec sp_serveroption 'srv_lnk','rpc out','true'";
			String sql4 = "exec srv_lnk.HRJ9_NWSD.dbo.HPMS_SysMtn_DisableAasUser '"+status+"','"+softUserName+"','"+Operator+"'";
			String sql5 = "exec sp_dropserver 'srv_lnk','droplogins'";
			
			CommandSyncsql csql = new CommandSyncsql();
			csql.getV().add(sql1);
			csql.getV().add(sql2);
			csql.getV().add(sql3);
			csql.getV().add(sql4);
			csql.getV().add(sql5);
			
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert("错误", "网络连接失败", null);
				}

				@Override
				public void onSuccess(CommandSyncReturnObject result) {
					if (result.isB()) {
						Info.display("提示信息", "添加成功");
					} else {
						MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);
					}
				}
			});
		}	
	}
	
	private void commandPOS(String softUserName,int status){
		Date date = new Date();
		int year = date.getYear() + 1900;
		String months = "";
		if(date.getMonth() + 1 < 10){
			months = "0" + date.getMonth() + 1;
		}else
			months = String.valueOf(date.getMonth() + 1);
		int day = date.getDay();
		String days = "";
		if(day < 10){
			days = "0" + day;
		}else
			days = String.valueOf(day);
		String hours = "";
		if(date.getHours() < 10){
			hours = "0" + date.getHours();
		}else
			hours = String.valueOf(date.getHours());
		String min = "";
		if(date.getMinutes() < 10){
			min = "0" + date.getMinutes();
		}else
			min = String.valueOf(date.getMinutes());
		String sec = "";
		if(date.getSeconds() < 10){
			sec = "0" + date.getSeconds();
		}else
			sec = String.valueOf(date.getSeconds());
		
		String filename = "iouserctrl" + "_" + year + months + days +"_" + hours + min + sec + ".csv";
		String okname = "iouserctrl" + "_" + year + months + days +"_" + hours + min + sec + ".ok";
		
		openJsp(filename,okname,softUserName,status);
	}
	
	private native void openJsp(String filename,String okname,String softUserName,int status) /*-{
		var data = new Object();
		data["filename"] = filename;
		data["okname"] = okname;
		data["softUserName"] = softUserName;
		data["status"] = status;
		$wnd.jQuery.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
    	$wnd.jQuery.post("hr_jsp/fileToDisk.jsp",data,null);
	}-*/;
	
	private boolean commandSql(String sql) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								Info.display("提示信息", "添加成功");
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);
							}
						}
					});
		}
		return true;
	}
}
